package com.zhuhanpeng.cloud.spring.util;

import com.obs.services.ObsClient;
import com.obs.services.model.ObjectListing;
import com.obs.services.model.ObsBucket;
import com.obs.services.model.ObsObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class OBSUtils {
    private final Logger logger = LogManager.getLogger(this.getClass());
    private static final String endPoint = "obs.cn-east-3.myhuaweicloud.com";
    private static final String ak = "NBRNPUBOGEDBCP2QFXF4";
    private static final String sk = "9Hf39N5LbMWXPVbY1IVH3XHEpysob1hVaTLll6SP";
    public static String BUCKET_NAME = "ntlg-obs";


//
    // 创建ObsClient实例
    ObsClient obsClient = new ObsClient(ak, sk, endPoint);
    //文件上传
    public void ObsUpload(String bucketName, String key, InputStream inputStream) throws IOException {

        obsClient.putObject(bucketName, key, inputStream);
        obsClient.close();
    }

    //文件硬删除
    public  void deleteFile(String bucketName){
        obsClient.deleteObject(BUCKET_NAME, bucketName);
    }

    //控制层可调用该方法实现文件下载
    public void dowloadFile(HttpServletResponse response, InputStream inputStream, String fileName) {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] items = new byte[1024 * 10];
        int i = 0;
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            OutputStream outputStream = response.getOutputStream();
            BufferedOutputStream outputStream1 = new BufferedOutputStream(outputStream);
            while ((i = bufferedInputStream.read(items)) != -1) {
                outputStream1.write(items, 0, i);
                outputStream1.flush();
            }
            outputStream1.close();
            outputStream.close();
            bufferedInputStream.close();
            inputStream.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }

    public ObsObject getFile(String key) {
        ObsObject obsObject = obsClient.getObject(BUCKET_NAME, key);
        return obsObject;
    }

    //获取文件名
    public ObjectListing getFileList() {
        ObjectListing objectListing = obsClient.listObjects(BUCKET_NAME);
        return objectListing;
    }



}
